package com.zzyl.nursing.controller.member;


import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.ReservationCountByTimeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/member/reservation")
public class MemberReservationController extends BaseController {


    @Autowired
    private IReservationService reservationService;

    /**
     * 查询取消预约数量
     */
    @GetMapping("/cancelled-count")
    public AjaxResult cancelledCount() {
        Long loginUser = UserThreadLocal.get();

        try {
            // 获取用户取消预约数量
            Long count = reservationService.cancelledCount(loginUser);
            // 返回简单的数字结果
            return success(count);
        } catch (RuntimeException e) {
            // 如果取消次数超过3次，返回0
            if (e.getMessage().contains("当天取消预约次数大于3次")) {
                return success(0L);
            }
            throw e;
        }
    }

    /**
     * 查询每个时间段剩余预约次数
     */
    @GetMapping("/countByTime")
    public AjaxResult countByTime(@RequestParam("time") Long time) {

        List<ReservationCountByTimeVo> countByTime = reservationService.reservationCountByTime(time);
        return success(countByTime);
    }

    @PostMapping
    public AjaxResult add(@RequestBody ReservationDto reservationDto) {
        reservationService.add(reservationDto);
        return success();
    }

    @GetMapping("/page")
    public AjaxResult list(Reservation reservation) {
        startPage();
        List<Reservation> list = reservationService.selectReservationList(reservation);
        return success(getDataTable(list));

    }

    @PutMapping("/{id}/cancel")
    public AjaxResult cancel(@PathVariable("id") Long id) {
        Long userId = UserThreadLocal.getUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        reservationService.cancelUpdate(id);
        return success();
    }



}
